package com.superatom.concurrent.share;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EvenChecker implements Runnable{
    // 这个生产者会被多条任务（线程）共享
    private IntGenerator generator;
    private final int id;

    public EvenChecker(IntGenerator g, int ident){
        generator = g;
        id = ident;
    }

    public void run() {
        while (!generator.isCanceled()){
            // 这步涉及到多条线程占用统一资源
            int val = generator.next();
            if (val % 2 != 0){
                System.out.println(val + " not even!");
                generator.cancel();
            }
        }
    }

    public static void test(IntGenerator gp, int count){
        System.out.println("Press Control-C to exit");
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < count; i++) {
            exec.execute(new EvenChecker(gp, i));
        }
        exec.shutdown();
    }

    public static void test(IntGenerator gp){
        test(gp, 10);
    }
}
